import React, { useReducer, useEffect, useState } from "react";
import { Alert } from "react-native";
import queryApi from "../../api/query";
import AsyncStorage from "@react-native-async-storage/async-storage";
import { fileWeb } from "../../api/query";
import axios from "axios";
import { uploadFileByS3, deleteFileByS3 } from "../../utils/s3FileUpload";
const GoodsContext = React.createContext();

const dataReducer = (state, action) => {
  switch (action.type) {
    case "fetch_init":
      return action.payload;
    case "addGoods":
      return [...state, action.payload];
    case "editGoods":
      return state.map((item) => {
        return item._id === action.payload._id ? action.payload : item;
      });
    case "deleteGoods":
      return state.filter((goods) => goods._id !== action.payload);
    case "filterGoods":
      return action.payload;
    case "reFetchGoods":
      return action.payload;
    default:
      return state;
  }
};

export const GoodsProvider = ({ children }) => {
  const [Goods, dispatch] = useReducer(dataReducer, []);
  const [isGoodsLoading, setIsGoodsLoading] = useState(false);
  const [isGoodsError, setIsGoodsError] = useState(false);
  const [goods, setGoods] = useState([]);
  const shapes = ["长方形", "圆形"];

  useEffect(() => {
    const fetchData = async () => {
      setIsGoodsLoading(true);
      setIsGoodsError(false);
      try {
        const token = await AsyncStorage.getItem("token");
        if (!token) {
          console.log("请求userId出错");
        }
        const result = await queryApi.get("/goods/", {
          headers: { Authorization: token },
        });
        // console.log("企业商品--", result.data.data);
        dispatch({ type: "fetch_init", payload: result.data.data });
        setGoods(result.data.data);
      } catch (err) {
        setIsGoodsError(true);
        console.log(err);
      }
      setIsGoodsLoading(false);
    };
    fetchData();
  }, []);

  const addGoods = async (newgoods, callback, setIsLoading) => {
    try {
      const token = await AsyncStorage.getItem("token");
      if (!token) {
        console.log("请求userId出错");
      }
      console.log("开始------");

      const imageUrl = await uploadFileByS3(newgoods.image);
      newgoods.image = imageUrl;

      const newGoods = await queryApi.post("/goods", newgoods, {
        headers: { Authorization: token },
      });
      console.log("添加商品信息后~:", newGoods.data.data);
      dispatch({ type: "addGoods", payload: newGoods.data.data });
      let arr = [...goods, newGoods.data.data];
      setGoods(arr);
      setIsLoading();
      Alert.alert("", "添加商品信息成功", [
        {
          text: "确定",
          onPress: () => {
            callback();
          },
        },
      ]);

      // let formData = new FormData();
      // // console.log("即将添加的商品---", newgoods);
      // newgoods.image.forEach((item) => {
      //   formData.append("files", {
      //     name: item.uri.split("/").pop(),
      //     uri: item.uri,
      //     type: "image/" + item.uri.split(".").pop(),
      //   });
      // });
      // // console.log("formdata", formData);

      // let res = await fetch(fileWeb + "/upload/multi", {
      //   method: "post",
      //   headers: {
      //     "Content-Type": "multipart/form-data",
      //   },
      //   body: formData,
      // });
      // let response = await res.json(); // if you do not use the await,you are logging the promise before it resolves
      // console.log("返回来的数据~", response.message);

      // let image = [];
      // image.push(result);
      // newgoods.image = image;

      // const newGoods = await queryApi.post("/goods", newgoods, {
      //   headers: { Authorization: token },
      // });
      // console.log("添加商品信息后~:", newGoods.data.data);
      // dispatch({ type: "addGoods", payload: newGoods.data.data });
      // let arr = [...goods, newGoods.data.data];
      // setGoods(arr);
      // Alert.alert("", "添加商品信息成功", [
      //   {
      //     text: "确定",
      //     onPress: () => callback(),
      //   },
      // ]);
    } catch (err) {
      setIsLoading();
      Alert.alert("", "添加商品信息失败");
      console.log("添加公司商品出错", err);
    }
  };

  const editGoods = async (
    newgoods,
    originImages,
    deleteImages,
    callback,
    setIsLoading
  ) => {
    try {
      // let formData = new FormData();
      //需新增图片
      // newgoods.image.forEach((item) => {
      //   formData.append("files", {
      //     name: item.uri.split("/").pop(),
      //     uri: item.uri,
      //     type: "image/" + item.uri.split(".").pop(),
      //   });
      // });
      const newUris = await uploadFileByS3(newgoods.image);
      //需删除图片
      // deleteImages.forEach((item) => {
      //   formData.append("idGroup[]", item._id);
      // });
      if (deleteImages.length !== 0) {
        await deleteFileByS3(deleteImages);
      }

      //需保留图片
      // originImages.forEach((item, i) => {
      //   formData.append("origin[]", item._id);
      // });
      // console.log("formdata", formData);

      // let res = await fetch(fileWeb + "/upload/multi", {
      //   method: "patch",
      //   headers: {
      //     "Content-Type": "multipart/form-data",
      //   },
      //   body: formData,
      // });
      // let response = await res.json(); // if you do not use the await,you are logging the promise before it resolves
      // console.log("返回来的数据~", response.message);

      // newgoods.image = response.message;
      // console.log("待修改数据---", newgoods);
      newgoods.image = originImages;
      newUris.forEach((uri) => {
        newgoods.image.push(uri);
      });

      const token = await AsyncStorage.getItem("token");
      if (!token) {
        console.log("请求userId出错");
      }

      const newGoods = await queryApi.patch(
        "/goods/" + newgoods._id,
        newgoods,
        {
          headers: { Authorization: token },
        }
      );
      dispatch({ type: "editGoods", payload: newGoods.data.message });

      let arr = goods.map((item) => {
        return item._id === newGoods.data.message._id
          ? newGoods.data.message
          : item;
      });
      setGoods(arr);
      setIsLoading();
      Alert.alert("", "修改商品信息成功", [
        {
          text: "确定",
          onPress: () => callback(newGoods.data.message),
        },
      ]);
      console.log("修改商品信息成功");
    } catch (err) {
      setIsLoading();
      console.log("编辑公司商品出错", err);
      Alert.alert("", "修改商品信息失败");
    }
  };

  const deleteGoods = async (deleted, setIsLoading) => {
    try {
      // let idGroup = deleted.image.map((item) => {
      //   return item._id;
      // });
      // await axios.delete(fileWeb + "/upload/multi", { data: idGroup });

      await deleteFileByS3(deleted.image);
      await queryApi.delete("/goods/" + deleted._id);
      dispatch({ type: "deleteGoods", payload: deleted._id });
      let arr = goods.filter((goods) => goods._id !== deleted._id);
      setIsLoading();
      setGoods(arr);
      Alert.alert("", "删除商品信息成功");
    } catch (err) {
      setIsLoading();
      console.log("删除公司商品出错", err);
      Alert.alert("", "删除商品信息失败");
    }
  };

  const filterGoods = (result, goodsFilter) => {
    const filterShape = (shape) => {
      if (goodsFilter[4] === -1 || shapes[goodsFilter[4]] === shape) {
        return true;
      } else {
        return false;
      }
    };

    const filterBasePlate = (baseplate) => {
      if (goodsFilter[0] === -1) {
        return true;
      } else if (
        goodsFilter[1] === -1 &&
        baseplate.category === result[goodsFilter[0]].category
      ) {
        return true;
      } else if (
        baseplate.category === result[goodsFilter[0]].category &&
        baseplate.type === result[goodsFilter[0]].types[goodsFilter[1]]
      ) {
        return true;
      } else {
        return false;
      }
    };

    const filterShroudPlate = (shroudplate) => {
      if (goodsFilter[2] === -1) {
        return true;
      } else if (
        goodsFilter[3] === -1 &&
        shroudplate.category === result[goodsFilter[2]].category
      ) {
        return true;
      } else if (
        shroudplate.category === result[goodsFilter[2]].category &&
        shroudplate.type === result[goodsFilter[2]].types[goodsFilter[3]]
      ) {
        return true;
      } else {
        return false;
      }
    };
    let list = goods;
    if (goodsFilter.length !== 0) {
      list = goods.filter((item) => {
        return (
          filterShape(item.shape) &&
          filterBasePlate(item.baseplate) &&
          filterShroudPlate(item.shroudplate)
        );
      });
    }

    dispatch({ type: "filterGoods", payload: list });
  };

  const resetGoods = () => {
    dispatch({ type: "filterGoods", payload: goods });
  };

  const regetGoods = async () => {
    try {
      const token = await AsyncStorage.getItem("token");
      if (!token) {
        console.log("请求userId出错");
      }
      const result = await queryApi.get("/goods/", {
        headers: { Authorization: token },
      });
      dispatch({ type: "reFetchGoods", payload: result.data.data });
      setGoods(result.data.data);
    } catch (err) {
      console.log("重新获取商品失败", err);
    }
  };

  return (
    <GoodsContext.Provider
      value={{
        Goods: Goods,
        addGoods,
        editGoods,
        deleteGoods,
        isGoodsError,
        isGoodsLoading,
        filterGoods,
        goods,
        resetGoods,
        regetGoods,
      }}
    >
      {children}
    </GoodsContext.Provider>
  );
};

export default GoodsContext;
